package com.liu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.common.R;
import com.liu.dto.DishDto;
import com.liu.entity.Category;
import com.liu.entity.Dish;
import com.liu.entity.DishFlavor;
import com.liu.service.CategoryService;
import com.liu.service.DishFlavorService;
import com.liu.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;


    @Resource
    private CategoryService categoryService;

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping()
    public R<String> save(@RequestBody DishDto dishDto) {

        dishService.saveDishWithFlavor(dishDto);

        //清除Redis缓存 全部清理
        //String keys = "dish_*";
        //redisTemplate.delete(keys);

        //清除Redis缓存 精确清理
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("添加菜品成功");
    }


    /**
     * 管理后台分页查询菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //创建条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件
        dishLambdaQueryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行查询
        dishService.page(dishPage, dishLambdaQueryWrapper);

        //将dishPage对象中除了records字段的全部内容拷贝到DishDto中
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //获取dishPage对象中的records字段，即List<Dish> dishes
        List<Dish> dishes = dishPage.getRecords();

        List<DishDto> list = dishes.stream().map(item -> {
            DishDto dishDto = new DishDto();

            //拷贝Dish对象到DishDto中
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());

        //将list赋值给dishDtoPage的records字段
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {

        DishDto dishDto = dishService.getDishWithFlavor(id);

        return R.success(dishDto);
    }

    @DeleteMapping()
    public R<String> delete(@RequestParam List<Long> ids) {
        //删除菜品
        dishService.removeWithFlavor(ids);

        return R.success("删除菜品成功");
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping()
    public R<String> update(@RequestBody DishDto dishDto) {

        dishService.updateDishWithFlavor(dishDto);

        //清除Redis缓存 全部清理
        //String keys = "dish_*";
        //redisTemplate.delete(keys);

        //清除Redis缓存 精确清理
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }


    /**
     * 跟新菜品售卖状态 1->0 起售->停售
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> stopSell(@RequestParam List<Long> ids) {
        //更新菜品售卖状态
        dishService.update(new UpdateWrapper<Dish>().set("status", 0).in("id", ids));

        return R.success("修改菜品状态成功");
    }


    /**
     * 跟新菜品售卖状态 0->1 停售->起售
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> startSell(@RequestParam List<Long> ids) {
        //更新菜品售卖状态
        dishService.update(new UpdateWrapper<Dish>().set("status", 1).in("id", ids));

        return R.success("修改菜品状态成功");
    }


    /**
     * （用户端）查询菜品信息
     * @param dish
     * @param name
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish,String name) {

        List<DishDto> dishDtoList = null;

        //从Redis缓存中查询菜品信息
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus(); //dish_1397844263642378242_1
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //缓存中有则直接返回缓存数据，没有数据，则查询数据库
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.like(name != null, Dish::getName, name);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //将查询结果缓存到Redis中
        redisTemplate.opsForValue().set(key, dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
// 其他方法...
